package com.wonder.common.utils;



import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;

@Slf4j
public class DesUtil {
	

    /**
     * 加密解密算法
     */
    private final static String ALGORITHM = "DES";

    /**
     * 默认编码
     */
    private static final String DEFAULT_CHAR_SET = "UTF-8";

    /**
     * 加密解密KEY
     */
    private static final String KEY = "5e1de9b31ca1440352352580905dba949860ccec";

    /**
     * 加密
     *
     * @param plaintext 未加密数据
     * @param key       加密key
     */
    public static String encrypt(String plaintext)  {
        try {
            byte[] dataBytes = plaintext.getBytes(DEFAULT_CHAR_SET);
            byte[] keyBytes = KEY.getBytes(DEFAULT_CHAR_SET);

            SecretKey secretKey = getSecretKey(keyBytes);
            SecureRandom random = getSecureRandom();
            Cipher cipher = getCipher();

            // 用密匙初始化Cipher对象
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, random);

            // 正式执行加密操作
            byte[] bytes = cipher.doFinal(dataBytes);
            return byte2hex(bytes);
        } catch (Exception e) {
            log.error("method=encrypt() is error, error_msg:{}, error:{}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * 解密
     *
     * @param ciphertext 加密后的数据
     * @param key        加密key
     * @return
     * @throws Exception
     */
    public static String decrypt(String ciphertext) {

        try {
            byte[] dataBytes = ciphertext.getBytes(DEFAULT_CHAR_SET);
            byte[] hex2byte = hex2byte(dataBytes);
            byte[] keyBytes = KEY.getBytes(DEFAULT_CHAR_SET);

            SecretKey secretKey = getSecretKey(keyBytes);
            SecureRandom random = getSecureRandom();
            Cipher cipher = getCipher();

            // 用密匙初始化Cipher对象
            cipher.init(Cipher.DECRYPT_MODE, secretKey, random);

            // 正式执行解密操作
            byte[] doFinal = cipher.doFinal(hex2byte);

            return new String(doFinal, DEFAULT_CHAR_SET);
        } catch (Exception e) {
            log.error("method=encrypt() is error, error_msg:{}, error:{}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * DES算法要求有一个可信任的随机数源
     */
    private static SecureRandom getSecureRandom() throws Exception {
        return new SecureRandom();
    }

    /**
     * 创建一个密匙工厂，然后用它把DESKeySpec对象转换成一个SecretKey对象
     */
    private static SecretKey getSecretKey(byte[] keyBytes) throws Exception {
        // 从原始密匙数据创建一个DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(keyBytes);
        // 创建一个密匙工厂，然后用它把DESKeySpec对象转换成一个SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        return keyFactory.generateSecret(dks);
    }

    /**
     * Cipher对象实际完成解密操作
     */
    private static Cipher getCipher() throws Exception {
        return Cipher.getInstance(ALGORITHM);
    }

    /**
     * 把16进制字符串转换成字节数组
     */
    private static byte[] hex2byte(byte[] bytes) throws Exception {
        final int temp = 2;
        if ((bytes.length % temp) != 0) {
            throw new IllegalArgumentException("长度不是偶数");
        }
        byte[] bte = new byte[bytes.length / temp];
        for (int n = 0; n < bytes.length; n += temp) {
            String item = new String(bytes, n, temp, DEFAULT_CHAR_SET);
            bte[n / temp] = (byte) Integer.parseInt(item, 16);
        }
        return bte;
    }

    /**
     * 把字节数组转换成16进制字符串
     */
    private static String byte2hex(byte[] bytes) throws Exception {
        StringBuilder bulid = new StringBuilder();
        String stmp;
        for (byte bte : bytes) {
            stmp = (Integer.toHexString(bte & 0XFF));
            if (stmp.length() == 1) {
                bulid.append("0").append(stmp);
            } else {
                bulid.append(stmp);
            }
        }
        return bulid.toString();
    }

//    public static void main(String[] args) throws Exception {
//        String content = "https://server8920.613518.com";
//        String str = DesUtil.encrypt(content, KEY);
//        System.out.println("plaintext: " + str);
//        str = DesUtil.decrypt(str, KEY);
//        System.out.println("ciphertext: " + str);
//    }

}
